local handler = require "handler"
local util = require "util"
local utils = require "utils"
local reason = require "reason"
local error_code = require "error_code"
local constant = require "constant"
local cocall = require "cocall"
local game_def = require "game_def"

local table_insert = table.insert
local table_sort = table.sort
local math_floor = math.floor
local notify_money_changed = handler.notify_money_changed
local add_awards = handler.add_awards
local tostring = tostring

local welfare_handler = {}

local function reset_month_salary(player)
    local uid = player.uid
    local user_data = player.user_data
    local sign_award_conf = global_configs.sign_award
    local sign_info = user_data.welfare_sign_info

    local ok,vip_level = R().basesvr({key=uid}):call('.msg_handler','get_vip_level',uid)
    if not ok then
        send_to_gateway('welfare.RSP_SIGN_INFO',{result = -2})
        return
    end

    for _,v in ipairs(vip_conf) do
        if v.level == vip_level then 
            month_reward = v.month_reward
        end
    end


    if sign_info.month_state == 0 and sign_info.sign_count >= sign_award_conf.days_param and sign_info.month_water >= salary_water_param then
        sign_info.month_state = 1
        sign_info.month_salary = month_reward
        send_to_gateway('hall.NTF_RED_POINTS',{
            module_list = {constant.MODULE_DEF.WELFARE}
        })
    end
    sign_info.sign_count = 0  --当月累计签到次数
    sign_info.month_water = 0 --当月流水
end

local function get_vip_salary_water_param(vip_level)
    for k,v in pairs(global_configs.vip) do
        if v.level == vip_level then
            return v.salary_water_param
        end
    end
end

function welfare_handler.REQ_VIP_WELFARE_INFO(msg)
    local vip_conf = global_configs.vip
    local uid = player.uid
    local user_data = player.user_data
    local vip_award_info = user_data.vip_award_info

    local ok,data = R().basesvr({key=uid}):call('.msg_handler','get_welfare_info',uid)
    if not ok then
        send_to_gateway('welfare.RSP_VIP_WELFARE_INFO',{result = -2})
        return
    end
    
    local vip_level  = data.vip_level
    local max_vip_level = #vip_conf - 1
    local next_level = (vip_level+1 > max_vip_level) and  max_vip_level or (vip_level+1)
    local next_level_conf = utils.getDataBykv(vip_conf,"level",next_level)
    if not next_level_conf then
        return
    end
    
    local vip_exp = vip_level == max_vip_level and next_level_conf.charge_coins or data.person_water

    local info = {}
    local water_param = 0
    for _,v in ipairs(vip_conf) do
        if v.level ~= 0 then 
            local item = {
                award_coins = v.lvl_reward,
                water = v.month_reward,
                vip_level = v.level,
                status = vip_level >= v.level and 1 or 0,
            }
            local update = true

            for idx,value in pairs(vip_award_info) do
                if v.level == value.vip_level then
                    if value.status == 2 then
                        item.status = value.status
                    else
                        value.status = item.status
                    end
                    update = false
                    break
                end
            end

            if update then
                local found = user_data.vip_award_info:new_table_field(#user_data.vip_award_info + 1)
                found.vip_level = v.level
                found.status = item.status
            end

            if v.level == vip_level + 1 then
                water_param = v.charge_coins - data.person_water
            end

            table_insert(info, item)
        end
    end

    local rsp = {
        vip_level = data.vip_level,
        vip_level_max = max_vip_level,
        vip_exp = vip_exp,
        vip_exp_max = next_level_conf.charge_coins,
        info = info,
        water_param = water_param,
        all_water = data.person_water,
        water_today = data.person_water_today,
    }

    send_to_gateway('welfare.RSP_VIP_WELFARE_INFO',rsp)
end

function welfare_handler.REQ_SIGN_INFO(msg)
    local uid = player.uid
    local sign_award_conf = global_configs.sign_award
    local user_data = player.user_data
    local sign_info = user_data.welfare_sign_info
    local vip_conf = global_configs.vip
    local month_reward = 0
    
    player:check_time_cross()

    local ok,data = R().basesvr({key=uid}):call('.msg_handler','get_welfare_info',uid)
    if not ok then
        send_to_gateway('welfare.RSP_SIGN_INFO',{result = -2})
        return
    end

    for _,v in ipairs(vip_conf) do
        if v.level == data.vip_level then 
            month_reward = v.month_reward
        end
    end

    local salary_water_param = get_vip_salary_water_param(data.vip_level)

    local sign_award = global_configs.sign_award
    if sign_info.sign_state == 0 and data.today_pay_money >= sign_award_conf.sign_param then 
        sign_info.sign_state = 1
    end

    sign_info.month_water = sign_info.month_water or 0

    --特殊情况VIP升级了
    if sign_info.sign_count >= sign_award_conf.days_param and sign_info.month_water >= salary_water_param then
        if sign_info.month_state == 0 then
            sign_info.month_state = 1
        end
    elseif sign_info.month_state == 1 then
        sign_info.month_state = 0
    end

    local month = tonumber(os.date("%m",util.get_now_time() + player.diff_time))

    local rsp = {
        charge_coins_day = data.today_pay_money,
        charge_coins_param = sign_award_conf.sign_param,
        sign_awards = sign_award_conf.sign_award,
        sign_count = sign_info.sign_count,
        sign_param = sign_award_conf.days_param,
        salary = month_reward,
        sign_status = sign_info.sign_state,
        salary_status = sign_info.month_state,
        month = month,
        month_water = sign_info.month_water,
        month_water_param = salary_water_param,
    }

    return send_to_gateway('welfare.RSP_SIGN_INFO', rsp)
end

function welfare_handler.REQ_WATER_AWARD_CONFIG(msg)
    local uid = player.uid
    local data = {}
    local water_award = global_configs.water_award

    for _,v in ipairs(water_award) do
        local item = {
            min = v.min_water,
            max = v.max_water,
            rate = v.rate*100,
        }
        table_insert(data, item)
    end

    local ok,ret_data = R().basesvr({key=uid}):call('.msg_handler','get_welfare_info',uid)
    if not ok then
        send_to_gateway('welfare.RSP_WATER_AWARD_CONFIG',{result = -2})
        return
    end

    return send_to_gateway('welfare.RSP_WATER_AWARD_CONFIG', {result = error_code.RSP_SUCESS,info = data,water_today = ret_data.person_water_today,})
end

function welfare_handler.REQ_VIP_AWARD_CONFIG(msg)
    local data = {}
    local config = global_configs.vip

    for _,v in pairs(config) do
        if v.level ~= 0 then
            local item = {
                vip_level = v.level,
                water = v.charge_coins,
                award_coins = v.lvl_reward,
            }
            table_insert(data, item)
        end
    end

    return send_to_gateway('welfare.RSP_VIP_AWARD_CONFIG', {result = error_code.RSP_SUCESS,info = data})
end

function welfare_handler.REQ_SALARY_CONFIG(msg)
    local data = {}
    local config = global_configs.vip

    for _,v in ipairs(config) do
        if v.level ~= 0 then
            local item = {
                vip_level = v.level,
                salary = v.month_reward,
                water_param = v.salary_water_param,
            }
            table_insert(data, item)
        end
    end

    return send_to_gateway('welfare.RSP_SALARY_CONFIG', {result = error_code.RSP_SUCESS,info = data})
end

function welfare_handler.REQ_SIGN_DAY(msg)
    local uid = player.uid
    local sign_award_conf = global_configs.sign_award
    local user_data = player.user_data
    local sign_info = user_data.welfare_sign_info
    if sign_info.sign_state ~= 1 then
        return send_to_gateway('welfare.RSP_SIGN_DAY',{result = -2})
    end
    local ok,vip_level = R().basesvr({key=uid}):call('.msg_handler','get_vip_level',uid)
    if not ok then
        send_to_gateway('welfare.RSP_SIGN_DAY',{result = -2})
        return
    end
    local salary_water_param = get_vip_salary_water_param(vip_level)
    local coins = sign_award_conf.sign_award
    local exinfo = {channel = player.channel,cur_channel = player.cur_channel}
    local ok,succ,ret = R().basesvr({key=uid}):call('.msg_handler','add_coins',uid,coins,reason.SIGN_REWARD,exinfo)
    if ok and succ and ret then
        sign_info.sign_state = 2
        sign_info.sign_count = sign_info.sign_count + 1
        sign_info.month_water = sign_info.month_water or 0
        if sign_info.month_state == 0 and sign_info.sign_count >= sign_award_conf.days_param and 
            sign_info.month_water >= salary_water_param then
            sign_info.month_state = 1
            send_to_gateway('hall.NTF_RED_POINTS',{
                module_list = {constant.MODULE_DEF.WELFARE}
            })
        end
        notify_money_changed(uid,{coins = ret.curr})
        
        local data = {}
        data.uid = uid
        data.type = constant.DODULE_ID.SIGN_IN 
        data.key = ""..os.date("%Y%m%d%H%M%S") .."_".. data.type .. "_" .. math.random(1,10000)
        data.op = "partake_num"
        dbglog("_____opPartakeNum__", dump(data))
        billlog(data)
        return send_to_gateway('welfare.RSP_SIGN_DAY', {result = error_code.RSP_SUCESS,coins = coins,salary_status = sign_info.month_state}) 
    end
    return send_to_gateway('welfare.RSP_SIGN_DAY', {result = -2}) 
end

function welfare_handler.REQ_SIGN_MONTH(msg)
    local uid = player.uid
    local sign_award_conf = global_configs.sign_award
    local user_data = player.user_data
    local sign_info = user_data.welfare_sign_info
    local vip_conf = global_configs.vip
    
    player:check_time_cross()

    if sign_info.month_state ~= 1 then
        return send_to_gateway('welfare.RSP_SIGN_MONTH',{result = -2})
    end
    local exinfo = {channel = player.channel,cur_channel = player.cur_channel}
    local ok,succ,ret = R().basesvr({key=uid}):call('.msg_handler','add_coins',uid,sign_info.month_salary,reason.SALARY_MONTH,exinfo)
    if ok and succ and ret then
        sign_info.month_state = 0
        sign_info.month_salary = 0
        notify_money_changed(uid,{coins = ret.curr})
        return send_to_gateway('welfare.RSP_SIGN_MONTH', {result = error_code.RSP_SUCESS,coins = sign_info.month_salary}) 
    end
    return send_to_gateway('welfare.RSP_SIGN_MONTH', {result = -2}) 
end

function welfare_handler.REQ_VIP_LEAVE_REWARD(msg)
    local uid = player.uid
    local vip_level = msg.vip_level
    local user_data = player.user_data
    local vip_award_info = user_data.vip_award_info
    local vip_conf = global_configs.vip
    
    for _,v in pairs(vip_award_info) do
        if v.vip_level == vip_level and v.status == 1 then
            for idx,value in pairs(vip_conf) do
                local coins = value.lvl_reward
                if value.level == vip_level then
                    local exinfo = {channel = player.channel,cur_channel = player.cur_channel}
                    local ok,succ,ret = R().basesvr({key=uid}):call('.msg_handler','add_coins',uid,coins,reason.VIP_REWARD,exinfo)
                    if ok and succ and ret then
                        v.status = 2
                        notify_money_changed(uid,{coins = ret.curr})
                        return send_to_gateway('welfare.RSP_VIP_LEAVE_REWARD', {result = error_code.RSP_SUCESS,vip_level = vip_level,coins = coins}) 
                    end
                    dbglog("REQ_VIP_LEAVE_REWARD",vip_level,coins,vip_award_info)
                    return send_to_gateway('welfare.RSP_VIP_LEAVE_REWARD', {result = error_code.RSP_SUCESS}) 
                end
            end
        end
    end
    dbglog("REQ_VIP_LEAVE_REWARD",vip_level,vip_award_info)
    return send_to_gateway('welfare.RSP_VIP_LEAVE_REWARD', {result = error_code.RSP_SUCESS})  
end

function welfare_handler.REQ_WELFARE_STATUS(msg)
    local uid = player.uid
    local vip_welfare_status = 0
    local sign_welfare_status = 0

    local vip_conf = global_configs.vip
    local uid = player.uid
    local user_data = player.user_data
    local vip_award_info = user_data.vip_award_info
    local sign_award_conf = global_configs.sign_award

    local ok,data = R().basesvr({key=uid}):call('.msg_handler','get_welfare_info',uid)
    if not ok then
        send_to_gateway('welfare.RSP_WELFARE_STATUS',{result = -2})
        return
    end

    local water_param = 0
    for _,v in ipairs(vip_conf) do
        if v.level ~= 0 and data.vip_level >= v.level then 
            local key = true
            for idx,value in pairs(vip_award_info) do
                if v.level == value.vip_level then
                    if value.status == 1 then 
                        vip_welfare_status = 1
                    end

                    if value.status == 0 then
                        value.status = 1 
                        vip_welfare_status = 1
                    end

                    key = false
                    break
                end
            end
            if key then
                local found = vip_award_info:new_table_field(#vip_award_info + 1)
                found.vip_level = v.level
                found.status = 1
                vip_welfare_status = 1
            end
        end
    end

    if user_data.welfare_sign_info.sign_state == 0 and data.today_pay_money >= sign_award_conf.sign_param then 
        user_data.welfare_sign_info.sign_state = 1
    end

    if user_data.welfare_sign_info.sign_state == 1 then 
        sign_welfare_status = 1
    end

    if user_data.welfare_sign_info.month_state == 1 then 
        sign_welfare_status = 1
    end   

    return send_to_gateway('welfare.RSP_WELFARE_STATUS', {result = error_code.RSP_SUCESS,vip_welfare_status = vip_welfare_status , sign_welfare_status = sign_welfare_status})  
end

--------------------------------------------------------
handler.register_module_handlers('welfare',welfare_handler)
